package com.gitee.feizns.upload.config.interceptors;

import com.gitee.feizns.upload.domain.prop.AuthorizationConfigProperties;
import com.gitee.feizns.web.ex.UnauthorizedException;
import com.gitee.feizns.web.utils.RsaUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feizns
 * @since 2019/8/9
 */
public class AuthorizationInterceptor implements HandlerInterceptor {

    private AuthorizationConfigProperties properties;

    public AuthorizationInterceptor(AuthorizationConfigProperties properties) {
        this.properties = properties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ( handler instanceof HandlerMethod ) {
            if ( properties.isEnable() && hasAnnotation((HandlerMethod) handler) ) {
                String pwd = request.getHeader(properties.getHttpHeader());
                if ( pwd == null )
                    throw new UnauthorizedException();

                String ori = RsaUtils.getInstance().decrypt(pwd, RsaUtils.getInstance().getPrivateKey(properties.getPrivateKey()));
                if ( properties.getPwd().contains(ori) == false )
                    throw new UnauthorizedException();
            }
        }
        return true;
    }

    private boolean hasAnnotation(HandlerMethod method) {
        TokenValidate validate = method.getMethodAnnotation(TokenValidate.class);
        if ( validate == null )
            return method.getBeanType().isAnnotationPresent(TokenValidate.class);
        return true;
    }

}
